package com.stylefeng.guns.rest.modular.wz.api.v3;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotations.Version;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.StringUtils;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.*;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.api.v3.service.IWzAdvMapService;
import com.stylefeng.guns.rest.modular.wz.api.v3.service.IWzMapActivityService;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.controller.WzFinanceService;
import com.stylefeng.guns.rest.modular.wz.service.IWzCouponService;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzUserServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.AliPushUtil;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户表
 */
@RestController
@RequestMapping("/wz/api/v3/wzUser/")
public class WzUserApiV3 extends ApiBaseController {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzUserCouponMapper userCouponMapper;
    @Autowired
    private IWzCouponService couponService;
    @Autowired
    private IWzAdvMapService advMapService;
    @Autowired
    private IWzMapActivityService mapActivityService;
    @Autowired
    private WzUserServiceImpl userService;
    @Autowired
    private  WzUserMessageMapper userMessageMapper;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzCouponMapper couponMapper;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzFinanceService financeService;
    @Autowired
    private WzAdvMapStaffMapper advMapStaffMapper;
    @Autowired
    private WzMapRebateMapper mapRebateMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 礼券扫码
     */
    @PostMapping("couponScan")
    public Res couponScan(@RequestBody ParamMap paramMap) throws Exception{
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        Long  userCouponId = paramMap.getLongMisValid("userCouponId");
        WzUserCoupon userCoupon = userCouponMapper.selectById(userCouponId);
        WzCoupon coupon = couponMapper.selectById(userCoupon.getCouponId());
        Long advMapId = Long.parseLong(coupon.getAdvMapId());
        List<Object> userCodeList=advMapStaffMapper.selectObjs(new EntityWrapper<WzAdvMapStaff>().setSqlSelect("user_code AS userCode").eq("adv_map_id",advMapId));
        userCodeList.add(coupon.getUserCode());
        boolean f= userCodeList.contains(userCode);
        if(!f){
                return Res.fail("此用户扫码无效!");
        }
        if(userCoupon != null){
            userCoupon.setScanUserCode(userCode.toString());
            if(userCoupon.getStatus() != EnWzUser.COUPON_STATUS_NORMAL.getIndex()){
                return Res.fail("此券不可使用!");
            }
            if(userCoupon.getBeginTime().after(new Date())){
                return Res.fail("请在有效期内使用!");
            }
            if(userCoupon.getEndTime().before(new Date())){
                return Res.fail("请在有效期内使用!");
            }
            WzUser scanUser = cacheService.user(userCode);
            WzUser user = cacheService.user(userCoupon.getUserCode());
            userCoupon.setNickName(user.getNickName());
            userCoupon.setAvatarUrl(user.getAvatarUrl());
            userCoupon.setStatus(EnWzUser.COUPON_STATUS_USED.getIndex());
            userCoupon.setScanTime(new Date());
            userCoupon.setScanName(scanUser.getNickName());
            boolean r = financeService.couponScan(userCoupon,coupon);
            if(r){
                JSONObject j = new JSONObject();
                j.put("code","100");
                j.put("userCouponId",userCouponId);
                j.put("type", EnWz.SCAN_TYPE_Coupon.getIndex());
                j.put("msg","扫码成功");
                if(user.getMobileType() == 1){//ios
                    AliPushUtil.pushMessageToIOS("礼券扫码",userCoupon.getUserCode().toString(),j);
                }else if(user.getMobileType() == 2){
                    AliPushUtil.pushMessageToAndroid("礼券扫码",userCoupon.getUserCode().toString(),j);
                }
                return Res.success("扫码成功!");
            }
            return Res.fail("请重新扫码!");
        }
        return Res.fail("请重新扫码!");
    }

    /**
     * 消息中心
     */
    @PostMapping("indexMessageList")
    public Res indexMessageList(){
        //业务处理
        Res res = userService.indexMessageList();
        return res;
    }

    /**
     * 消息已读
     */
    @PostMapping("indexMessageRead")
    public Res indexMessageRead(@RequestBody ParamMap paramMap){
        Long userMessageId = paramMap.getLongMisValid("userMessageId");
        WzUserMessage userMessage = userMessageMapper.selectById(userMessageId);
        userMessage.setIsRead(1);
        int r = userMessageMapper.updateById(userMessage);
        if(r > 0){
            return Res.success();
        }
        return Res.fail();
    }

    /**
     * 我的礼券
     */
    @PostMapping("userCoupons")
    public Res userCoupons(@RequestBody ParamMap paramMap) {
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        int status = paramMap.getIntMisValid("status");//优惠券状态:1-可用;2-已使用/过期
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //过期礼券处理
        List<WzUserCoupon> userCouponList = userCouponMapper.selectList(new EntityWrapper<WzUserCoupon>().eq("user_code", userCode).lt("end_time", new Date()).eq("status", EnWzUser.COUPON_STATUS_NORMAL.getIndex()));
        for (WzUserCoupon userCoupon : userCouponList) {
            userCoupon.setStatus(EnWzUser.COUPON_STATUS_INVALID.getIndex());
            userCouponMapper.updateById(userCoupon);
        }
        EntityWrapper<WzUserCoupon> ew = new EntityWrapper<>();
        ew.eq("user_code", userCode).orderBy("end_time", true);
        if (status == EnWzCoupon.UserCoupon_Status_Normal.getIndex()) {//可使用
            ew.eq("status", EnWzCoupon.UserCoupon_Status_Normal.getIndex());
        }else if(status == EnWzCoupon.UserCoupon_Status_Used.getIndex()){//已使用
            ew.eq("status", EnWzCoupon.UserCoupon_Status_Used.getIndex());
        }else if(status == EnWzCoupon.UserCoupon_Status_Invalid.getIndex()){//已过期
            ew.eq("status", EnWzCoupon.UserCoupon_Status_Invalid.getIndex());
        }else if(status == EnWzCoupon.UserCoupon_Status_Refund.getIndex()){//已退款
            ew.eq("status", EnWzCoupon.UserCoupon_Status_Refund.getIndex());
        }
        WzUser user = cacheService.user(userCode);
        List<SysUser> sysUserList = sysUserMapper.selectList(new EntityWrapper<SysUser>().eq("phone", user.getAccount()).eq("status",1));//是否是管理员
        String sql = "coupon_id As couponId,buyer_id As buyerId,type,market_rebate_profit As marketRebateProfit,price,name,logo,user_coupon_id As userCouponId,coupon_id As couponId,pic,adv_map_id As advMapId,subtype,status,benefit,rule,begin_time As beginTime,end_time As endTime";
        List<Map<String, Object>> userCoupons = userCouponMapper.selectMapsPage(new Page<>(pageNum, pageSize), ew.setSqlSelect(sql));
        for(Map userCoupon:userCoupons){
            userCoupon.put("isRefund", 1);
            if(Integer.parseInt(userCoupon.get("type").toString()) == EnWzCoupon.TYPE_Prize.getIndex()){
                userCoupon.put("isRefund", 0);
            }
            if(Integer.parseInt(userCoupon.get("type").toString()) == EnWzCoupon.TYPE_Merge.getIndex()){//拼单券
                if(sysUserList.size() <= 0){
                    userCoupon.put("isRefund", 0);
                }
            }
            if(StringUtils.isBlank(userCoupon.get("buyerId").toString())){
                userCoupon.put("isRefund", 0);
            }
            if(Integer.parseInt(userCoupon.get("type").toString()) == EnWzCoupon.TYPE_Rebate.getIndex() || Integer.parseInt(userCoupon.get("type").toString()) == EnWzCoupon.TYPE_Shopping.getIndex()){
                WzCoupon coupon = cacheService.coupon(Long.parseLong(userCoupon.get("couponId").toString()));
                userCoupon.put("rebatePrice",coupon.getPrice() - Integer.parseInt(userCoupon.get("price").toString()));
            }else{
                userCoupon.put("rebatePrice",0);
            }
            if(Integer.parseInt(userCoupon.get("type").toString()) == EnWzCoupon.TYPE_Shopping.getIndex()){
                userCoupon.put("price",Integer.parseInt(userCoupon.get("price").toString()) + Integer.parseInt(userCoupon.get("marketRebateProfit").toString()));
            }
            if(StringUtils.isBlank(userCoupon.get("benefit").toString())){
                Map coupon=cacheService.couponData(Long.parseLong(userCoupon.get("couponId").toString()));
                userCoupon.put("benefit",coupon.get("benefit"));
            }
            if(StringUtils.isBlank(userCoupon.get("name").toString())){
                WzAdvMap advMap = cacheService.advMap(Long.parseLong(userCoupon.get("advMapId").toString()));
                userCoupon.put("logo", advMap.getLogo());
                userCoupon.put("name", advMap.getName());
                userCoupon.put("longitude", advMap.getLongitude());
                userCoupon.put("latitude", advMap.getLatitude());
            }
        }
        return Res.success(paramMap.data(userCoupons));
    }

    /**
     * 我管理的店铺列表
     */
    @PostMapping("myStaffList")
    public Res myStaffList(@RequestBody ParamMap paramMap){
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //我参与管理的店铺列表
        List<Map<String,Object>> advMapStaffs=advMapStaffMapper.selectMaps(new EntityWrapper<WzAdvMapStaff>().setSqlSelect("adv_map_id AS advMapId").eq("user_code",userCode));
        //我的店铺列表
        List<Map<String,Object>> advMapList=advMapService.selectMaps(new EntityWrapper<WzAdvMap>().setSqlSelect("adv_map_id AS advMapId").eq("user_code",userCode).eq("status", EnWzAdvMap.STATUS_Release.getIndex()));
        advMapStaffs.addAll(advMapList);
        for(Map advMapstaff:advMapStaffs){
            WzAdvMap advMap=cacheService.advMap(Long.parseLong(advMapstaff.get("advMapId").toString()));
            advMapstaff.put("subtype",advMap.getSubtype());
            advMapstaff.put("avatarUrl",advMap.getAvatarUrl());
            advMapstaff.put("name",advMap.getName());
            advMapstaff.put("logo",advMap.getLogo());
            advMapstaff.put("latitude",advMap.getLatitude());
            advMapstaff.put("longitude",advMap.getLongitude());
            advMapstaff.put("subtitle",advMap.getSubtitle());
            advMapstaff.put("userCode", advMap.getUserCode());
            advMapstaff.put("merchantFullAddress", advMap.getMerchantFullAddress());
            advMapstaff.put("merchantTel", advMap.getMerchantTel());
            advMapstaff.put("shareLink", advMap.getShareLink());
        }
        return Res.success(advMapStaffs);
    }

}

